//
//  TKYMineController.m
//  StationHouseHelper
//
//  Created by apple on 2018/5/4.
//  Copyright © 2018年 铁科院. All rights reserved.
//

#import "TKYMineController.h"
#import "TKYSearchBarTextFiled.h"
#import "WMPageController.h"
#import "UIViewController+CWLateralSlide.h"
#import "ParentClassScrollViewController.h"
#import "MainTouchTableTableView.h"
#import "TKYSearchPersonController.h"
#import "DataModel.h"
#import "TKYChangeStationHouseController.h"
#import "TKYMessageCenterController.h"
#define Main_Screen_Height      [[UIScreen mainScreen] bounds].size.height
#define Main_Screen_Width       [[UIScreen mainScreen] bounds].size.width
@interface TKYMineController ()<UITableViewDelegate,UITableViewDataSource,scrollDelegate,WMPageControllerDelegate,UISearchBarDelegate>


@property(nonatomic ,strong)MainTouchTableTableView * mainTableView;

@property(nonatomic,strong) UIScrollView * parentScrollView;
@property (nonatomic, strong) UIView *headerView;


/**
 搜索框
 */
//@property (nonatomic, strong)TKYSearchBarTextFiled *searchBar;
@property(nonatomic,strong) UISearchBar *searchBar;// 搜索条



@end

@implementation TKYMineController
//- (void)viewDidAppear:(BOOL)animated
//{
//    [super viewDidAppear:animated];
//    if (!_searchBar.isFirstResponder) {
//        [self.searchBar becomeFirstResponder];
//    }
//}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.searchBar resignFirstResponder];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    //设置界面
    [self setUPUI];
    
    [self.view addSubview:self.mainTableView];
    
    [self setBarButtonItem];

   // [self.headerView addSubview: self.searchBar];
    self.mainTableView.tableHeaderView = self.headerView;
}



- (void)setBarButtonItem
{
    //创建searchBar
    UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 40)];
    //默认提示文字
    searchBar.placeholder = @"搜索内容";
    //背景图片
    //searchBar.backgroundImage = [UIImage imageNamed:@"clearImage"];
    //代理
    searchBar.delegate = self;
    //显示右侧取消按钮
    searchBar.showsCancelButton = YES;
    //光标颜色
    searchBar.tintColor = [UIColor redColor];
    //拿到searchBar的输入框
    UITextField *searchTextField = [searchBar valueForKey:@"_searchField"];
    //字体大小
    searchTextField.font = [UIFont systemFontOfSize:15];
    //输入框背景颜色
    searchTextField.backgroundColor = [UIColor colorWithRed:234/255.0 green:235/255.0 blue:237/255.0 alpha:1];
    //拿到取消按钮
    UIButton *cancleBtn = [searchBar valueForKey:@"cancelButton"];
    //设置按钮上的文字
    [cancleBtn setTitle:@"取消" forState:UIControlStateNormal];
    //设置按钮上文字的颜色
    [cancleBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.searchBar = searchBar;
    //self.navigationItem.titleView = titleView;
    [self.headerView addSubview:self.searchBar];
}
/**
 设置界面
 */
- (void)setUPUI{
    self.navigationItem.title = @"我的";
    self.navigationController.navigationBar.barTintColor = KNavColor;
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor whiteColor],NSFontAttributeName:[UIFont systemFontOfSize:19.0]}];
    
    if (@available(iOS 11.0, *)) {
        self.mainTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
     self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"nav"] style:UIBarButtonItemStylePlain target:self action:@selector(changeStationHouseBarButtonItem:)];
    
    //导航右侧的消息按钮
    UIButton *rightBarButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBarButton setImage:[UIImage imageNamed:@"message"] forState:UIControlStateNormal];
    rightBarButton.frame = CGRectMake(0, 0, 40, 40);
    [rightBarButton addTarget:self action:@selector(messageCerterAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:rightBarButton];
    // 1.2 右边
    [self.navigationItem.rightBarButtonItem pp_addBadgeWithText:nil];
    [self.navigationItem.rightBarButtonItem pp_moveBadgeWithX:0 Y:6];
    [self.navigationItem.rightBarButtonItem pp_setBadgeFlexMode:PPBadgeViewFlexModeHead];
    //隐藏消息按钮的小红点
    // [self.navigationItem.rightBarButtonItem pp_hiddenBadge ];
}

#pragma mark-- 按钮的点击事件
//切换站点
- (void)changeStationHouseBarButtonItem:(UIBarButtonItem *)barButtonItem{
    TKYChangeStationHouseController *vc = [[TKYChangeStationHouseController alloc] init];
    vc.drawerType = DrawerTypeMaskLeft;
    // [self cw_pushViewController:vc drewerHiddenDuration:0.01];
    [self cw_showDrawerViewController:vc animationType:CWDrawerAnimationTypeMask configuration:nil];
}

//切换消息界面
- (void)messageCerterAction:(UIBarButtonItem *)barButtonItem{
    TKYMessageCenterController *messageCenterVC = [TKYMessageCenterController new];
    
    [self.navigationController pushViewController:messageCenterVC animated:YES];
    
}

#pragma mark - UISearchBarDelegate
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    return YES;
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    searchBar.showsCancelButton = YES;
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    NSString *inputStr = searchBar.text;
    if (inputStr.length == 0)
    {
        self.memberVc.searchActive = NO;
        [self.memberVc.tableView reloadData];
        return;
    }
    self.memberVc.searchActive = YES;
    self.memberVc.resultData = [NSMutableArray array];
    self.memberVc.resultIndexData = [NSMutableArray array];
    
    dispatch_queue_t globalQueue = dispatch_get_global_queue(0, 0);
    dispatch_async(globalQueue, ^{
        //遍历需要搜索的所有内容，其中self.dataArray为存放总数据的数组
        [self.memberVc.tableData enumerateObjectsUsingBlock:^(NSMutableArray * obj, NSUInteger aIdx, BOOL * _Nonnull stop) {
            //刚进来 && 第一个数组不为空时 插入一个数组在第一个位置
            if (self.memberVc.resultData.count == 0 || [[self.memberVc.resultData lastObject] count] != 0)
            {
                [self.memberVc.resultData addObject:[NSMutableArray array]];
            }
            
            [obj enumerateObjectsUsingBlock:^(DataModel * model, NSUInteger bIdx, BOOL * _Nonnull stop) {
                
                NSString *tempStr = model.aName;
                //----------->把所有的搜索结果转成成拼音
                NSString *pinyin = [self transformToPinyin:tempStr isQuanPin:NO];
                
                if ([pinyin rangeOfString:searchBar.text options:NSCaseInsensitiveSearch].length > 0)
                {
                    //把搜索结果存放self.resultArray数组
                    [self.memberVc.resultData.lastObject addObject:model];
                    if (self.memberVc.resultIndexData == 0 || ![self.memberVc.resultIndexData.lastObject isEqualToString:self.memberVc.tableIndexData[aIdx]])
                    {
                        [self.memberVc.resultIndexData addObject:self.memberVc.tableIndexData[aIdx]];
                    }
                }
            }];
        }];
        //回到主线程
        if ([self.memberVc.resultData.lastObject count] == 0)
        {
            [self.memberVc.resultData removeLastObject];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.memberVc.tableView reloadData];
        });
    });

}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [self.searchBar resignFirstResponder];
    searchBar.text = @"";
    if (searchBar.text.length == 0)
    {
        self.memberVc.searchActive = NO;
        [self.memberVc.tableView reloadData];
        return;
    }
    
    //[self.navigationController popViewControllerAnimated:YES];
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
    searchBar.showsCancelButton = YES;
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    //加个多线程，否则数量量大的时候，有明显的卡顿现象
    //这里最好放在数据库里面再进行搜索，效率会更快一些
    //成员搜索
    if (searchText.length == 0)
    {
        self.memberVc.searchActive = NO;
        [self.memberVc.tableView reloadData];
        return;
    }
    self.memberVc.searchActive = YES;
    self.memberVc.resultData = [NSMutableArray array];
    self.memberVc.resultIndexData = [NSMutableArray array];
    
    dispatch_queue_t globalQueue = dispatch_get_global_queue(0, 0);
    dispatch_async(globalQueue, ^{
        //遍历需要搜索的所有内容，其中self.dataArray为存放总数据的数组
        [self.memberVc.tableData enumerateObjectsUsingBlock:^(NSMutableArray * obj, NSUInteger aIdx, BOOL * _Nonnull stop) {
            //刚进来 && 第一个数组不为空时 插入一个数组在第一个位置
            if (self.memberVc.resultData.count == 0 || [[self.memberVc.resultData lastObject] count] != 0)
            {
                [self.memberVc.resultData addObject:[NSMutableArray array]];
            }
            
            [obj enumerateObjectsUsingBlock:^(DataModel * model, NSUInteger bIdx, BOOL * _Nonnull stop) {
                
                NSString *tempStr = model.aName;
                //----------->把所有的搜索结果转成成拼音
                NSString *pinyin = [self transformToPinyin:tempStr isQuanPin:NO];
                
                if ([pinyin rangeOfString:searchText options:NSCaseInsensitiveSearch].length > 0)
                {
                    //把搜索结果存放self.resultArray数组
                    [self.memberVc.resultData.lastObject addObject:model];
                    if (self.memberVc.resultIndexData == 0 || ![self.memberVc.resultIndexData.lastObject isEqualToString:self.memberVc.tableIndexData[aIdx]])
                    {
                        [self.memberVc.resultIndexData addObject:self.memberVc.tableIndexData[aIdx]];
                    }
                }
            }];
        }];
        //回到主线程
        if ([self.memberVc.resultData.lastObject count] == 0)
        {
            [self.memberVc.resultData removeLastObject];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.memberVc.tableView reloadData];
        });
    });
}

//将汉字转为拼音 是否支持全拼可选
- (NSString *)transformToPinyin:(NSString *)aString isQuanPin:(BOOL)quanPin
{
    //转成了可变字符串
    NSMutableString *str = [NSMutableString stringWithString:aString];
    CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformMandarinLatin,NO);
    
    //再转换为不带声调的拼音
    CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics,NO);
    NSArray *pinyinArray = [str componentsSeparatedByString:@" "];
    NSMutableString *allString = [NSMutableString new];
    
    if (quanPin)
    {
        int count = 0;
        for (int  i = 0; i < pinyinArray.count; i++)
        {
            for(int i = 0; i < pinyinArray.count;i++)
            {
                if (i == count) {
                    [allString appendString:@"#"];
                    //区分第几个字母
                }
                [allString appendFormat:@"%@",pinyinArray[i]];
            }
            [allString appendString:@","];
            count ++;
        }
    }
    
    NSMutableString *initialStr = [NSMutableString new];
    //拼音首字母
    for (NSString *s in pinyinArray)
    {
        if (s.length > 0)
        {
            [initialStr appendString:[s substringToIndex:1]];
        }
    }
    [allString appendFormat:@"#%@",initialStr];
    [allString appendFormat:@",#%@",aString];
    return allString;
}

#pragma scrollDelegate
-(void)scrollViewLeaveAtTheTop:(UIScrollView *)scrollView
{
    self.parentScrollView = scrollView;
    //离开顶部 主View 可以滑动
    self.parentScrollView.scrollEnabled = NO;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    //获取滚动视图y值的偏移量
    CGFloat tabOffsetY = [self.mainTableView rectForSection:0].origin.y;
    CGFloat offsetY = scrollView.contentOffset.y;
    
    if (offsetY>=tabOffsetY) {
        scrollView.contentOffset = CGPointMake(0, tabOffsetY);
        self.parentScrollView.scrollEnabled = YES;
    }else{
    }
}

#pragma mark --tableDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return Main_Screen_Height-64;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    /* 添加pageView
     * 这里可以任意替换你喜欢的pageView
     *作者这里使用一款github较多人使用的 WMPageController 地址https://github.com/wangmchn/WMPageController
     */
    [cell.contentView addSubview:self.setPageViewControllers];
    
    return cell;
}

-(UIView *)setPageViewControllers
{
    WMPageController *pageController = [self p_defaultController];
    pageController.title = @"Line";
    pageController.menuViewStyle = WMMenuViewStyleLine;
    pageController.titleSizeSelected = 15;
    
    [self addChildViewController:pageController];
    [pageController didMoveToParentViewController:self];
    return pageController.view;
}

- (WMPageController *)p_defaultController {
    //准备要添加的控制器和标题数组
    self.memberVc = [[TKYMemberController alloc]init];
    self.companyVc = [[TKYCompanyController alloc]init];
    self.memberVc.delegate = self;
    self.companyVc.delegate = self;
    
    NSArray *viewControllers = @[self.memberVc,self.companyVc];
    
    NSArray *titles = @[@"按成员显示",@"按公司显示"];
    WMPageController *pageVC = [[WMPageController alloc] initWithViewControllerClasses:viewControllers andTheirTitles:titles];
    [pageVC setViewFrame:CGRectMake(0, 0, Main_Screen_Width, Main_Screen_Height)];
    pageVC.delegate = self;
    pageVC.menuItemWidth = 85;
    pageVC.titleColorSelected = KNavColor;
    pageVC.menuHeight = 44;
    pageVC.postNotification = YES;
    pageVC.bounces = YES;
    return pageVC;
}

- (void)pageController:(WMPageController *)pageController willEnterViewController:(__kindof UIViewController *)viewController withInfo:(NSDictionary *)info {
    
    
    NSLog(@"%@",viewController);
}

-(MainTouchTableTableView *)mainTableView{
    if (_mainTableView == nil)
    {
        _mainTableView= [[MainTouchTableTableView alloc]initWithFrame:CGRectMake(0,MyNavBarHeight,Main_Screen_Width,Main_Screen_Height- MyNavBarHeight)];
        _mainTableView.delegate=self;
        _mainTableView.dataSource=self;
        _mainTableView.showsVerticalScrollIndicator = NO;
        // _mainTableView.contentInset = UIEdgeInsetsMake(headViewHeight,0, 0, 0);
        _mainTableView.backgroundColor = [UIColor clearColor];
    }
    return _mainTableView;
}

- (UIView *)headerView{
    if (_headerView == nil) {
        _headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kHeightScale *40)];
        //_headerView.backgroundColor = [UIColor redColor];
    }
    return _headerView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
    
@end
